﻿//----------------------------------------------------------------
// Copyright (c) 2011-2013 
// All rights reserved.
// Author: Ben DaoWei 
// Contact: bendaowei@gmail.com
// Web Link: http://xnaeditor.codeplex.com
// ----------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine.Components;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using UnityEngine.Graphics.Shader;

namespace UnityEngine.Graphics.Light
{
    public class ShadowMap : IDisposable
    {
        private Camera _Camera;
        private RenderTarget2D _RenderTareget;

        ~ShadowMap()
        {
            this.Dispose(false);
        }
        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_RenderTareget != null)
                    _RenderTareget.Dispose();
            }
        }

        public void UpdateShadowMap()
        {
            EffectManager.Instance.Shader.IsCreateShadow = true;
            EffectManager.Instance.GraphicsDevice.SetRenderTarget(_RenderTareget);
            EffectManager.Instance.GraphicsDevice.Clear(Color.White);
            EffectManager.Instance.Shader.EyeViewProjection = _Camera.View * _Camera.Projection;
            SceneManager.Instance.RenderForShadow();
            EffectManager.Instance.GraphicsDevice.SetRenderTarget(null);
            EffectManager.Instance.Shader.ShadowMap = _RenderTareget;
            EffectManager.Instance.Shader.IsCreateShadow = false;
        }

        public void Startup(GameTime gameTime)
        {
            _Camera = new Camera();
            _Camera.Position = new Vector3(8192, 4000, 8192);
            _Camera.LookAt = new Vector3(8192, 0, 8192);
            _Camera.Up = new Vector3(0.8f, 0.5f, 0.0f);

            _Camera.View = Matrix.CreateLookAt(_Camera.Position, _Camera.LookAt, _Camera.Up);
            _Camera.Projection = Matrix.CreateOrthographic(128 * 128, 128 * 128, 1, 4000);

            _RenderTareget = new RenderTarget2D(EffectManager.Instance.GraphicsDevice, 2048, 2048);
        }
    }
}
